<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="30" style="padding-left: 20px">
      <el-col :span="6" style="display: flex; align-items: center">
        <span style="width: 90px; color: #666666; font-size: 13px">所属公司：</span>
        <el-select clearable v-model="queryForm.query.companyId"
                   placeholder="请选择所属公司">
          <el-option v-for="(item, index) in companyList" :key="index"
                     :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="display: flex; align-items: center">
        <span style="width: 90px; color: #666666; font-size: 13px">部门名称：</span>
        <el-input placeholder="请输入部门名称搜索" v-model="queryForm.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="searchData">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="edit">创建部门</el-button>
      </el-col>
    </el-row>
    <hawk-table v-model="multipleSelection" :table-data="tableData"
                :page="queryForm.page" :number="true"
                @selectionChange="handleSelectionChange" :options="[
        { key: 'name', label: '部门名称' },
        { key: 'company', label: '所属公司' },
        { key: 'createTime', label: '创建时间' },
        { key: 'handle', label: '操作' },
      ]">

      <template #company="{ row }">
        <span>{{ row.company.name }}</span>
      </template>

      <template #createTime="{ row }">
        <span>{{ transformDateFormat(row.createTime, 'yyyy-MM-dd hh:mm:ss') }}</span>
      </template>

      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="edit(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="del(row)">删除</span>
      </template>
    </hawk-table>
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="multiDel">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>
    
    <el-dialog :title="formTitle" :visible.sync="addDialogVisible" width="20%"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form label-position="right" :model="addForm" :rules="addFormRules"
               ref="addFormRef" label-width="90px">

        <el-form-item label="所属公司" prop="companyId">
          <el-select clearable v-model="addForm.companyId"
                     @change="selectedCompanyChange">
            <el-option v-for="(item, index) in companyList" :key="index"
                       :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author 韩梦远
 * @description 部门字典
 * @api 后台接口地址
 * @since 2021-11-08
 * @update 代码更新时间
 * @modifier 修改人
 * @bug 无
 * @version v1.0.0
 */
import {
  getList,
  doDelete,
  doAdd,
  isNameHave,
  doEdit,
} from '@/api/assets/dictionaries/department'
import { getAllCompany as getCompany } from '@/api/assets/dictionaries/company'

export default {
  data () {

    let nameValide = async (rule, value, callback) => {

      if (!value) {
        return
      }

      let companyId = this.addForm.companyId
      if (!companyId || companyId == '') {
        callback('请先选择公司 ')
        return
      }

      console.log(value);
      let ret = await isNameHave(companyId, value)
      console.log(ret);
      if (ret.code == 20000 && ret.data) {
        callback(new Error(`该公司已经有${value}部门`))
        return
      }

      callback()


    }



    return {
      companyList: [],
      multipleSelection: [],
      addDialogVisible: false,
      formTitle: '',
      total: 0,
      queryForm: {
        query: {
          name: '',
          companyId: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      tableData: [],
      addForm: {
        name: '',
        companyId: '',
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入部门', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '部门的长度在2-20个字符之间',
          },
          { validator: nameValide, trigger: 'blur' }

        ],
        companyId: [{ required: true, message: '请选择公司', trigger: 'blur' }],
      },
    }
  },
  async created () {
    this.init()
    this.getcompanyList()
  },
  methods: {

    selectedCompanyChange () {
      let companyId = this.addForm.companyId
      if (!companyId || companyId == '') {
        return
      }

      if (this.addForm.name) {
        this.$refs.addFormRef.validateField('name');
      }


    },
    async getcompanyList () {
      const res = await getCompany()
      console.log(res);
      this.companyList = res.data
      // let obj = {
      //   company: '请选择所属公司',
      //   id: 0,
      // }
      // this.companyList.unshift(obj)
    },
    async searchData () {
      this.queryForm.page.current = 1
      this.multipleSelection = []
      this.init()
    },
    reSet () {
      this.queryForm = this.$options.data().queryForm
      this.init()
    },
    async init () {
      const ret = await getList(this.queryForm)
      this.tableData = ret.data.records
      console.log(ret)
      this.total = ret.data.total
    },
    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },
    handleCurrentChange (val) {
      this.queryForm.page.current = val
      this.init()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    //批量删除
    multiDel () {
      let list = []
      this.multipleSelection.forEach((item) => {
        list.push(item.id)
      })
      // console.log(list);
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete(list)
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }

        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    edit (row) {
      if (!row.id) {
        this.formTitle = '创建部门'
      } else {
        this.formTitle = '修改部门'
        this.addForm = Object.assign({}, row)
      }
      this.addDialogVisible = true
    },
    addDialogClosed () {
      this.addForm = this.$options.data().addForm
      // this.$refs.addFormRef.clearValidate();   //清除表单校验
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = false


      this.init()

    },
    save () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        if (this.addForm.id) {
          console.log("--EDIT-");
          await doEdit(this.addForm)
          this.multipleSelection = []
        } else {
          // 新建
          console.log("--add-");
          let ret = await doAdd(this.addForm)
          console.log(ret);

          this.multipleSelection = []
        }
        this.addDialogClosed()
      })
    },
    del (row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.id])
          console.log(ret);
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>
<style lang="scss" scoped></style>